package com.huffman.smart_picture.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.utils.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author DengLin
 * @date 2025/1/18 14:56
 * @description: url图片上传
 */
@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate {

    private static final List<String> URL_CONNECT_ALLOW_TYPE = Arrays.asList("image/jpg", "image/png", "image/jpeg", "image/webp");

    @Override
    protected void validPicture(Object inputSource,boolean isAdmin) {
        String pictureUrl = (String) inputSource;
        ThrowUtil.throwIf(!StringUtils.hasText(pictureUrl), ErrorEnum.PARAM_EMPTY, "图片url为空");
        //处理转义字符
        if (!isAdmin){
            int questionMarkIndex = pictureUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                pictureUrl = pictureUrl.substring(0, questionMarkIndex);
            }
        }
        // 校验url是否合法
        try {
            new URL(pictureUrl);
        } catch (MalformedURLException e) {
            log.error("upload url mistake:{}", e.getMessage());
            throw new BusinessException(ErrorEnum.PARAM_CHECK_MISTAKE, "url地址不合法");
        }

//        ThrowUtil.throwIf(!((pictureUrl.startsWith("http://") || pictureUrl.startsWith("https://"))),
//                ErrorEnum.PARAM_ILLICIT, "仅支持HTTP或HTTPS文件协议");

        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, pictureUrl).execute();
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            String contentType = response.header("Content-Type");
            ThrowUtil.throwIf(!URL_CONNECT_ALLOW_TYPE.contains(contentType.toLowerCase()), ErrorEnum.PARAM_ILLICIT, "文件类型错误");
            String contentLength = response.header("Content-Length");
            if (StringUtils.hasText(contentLength)) {
                // 不是管理员 限制文件大小上传
                if (!isAdmin) {
                    try {
                        long size = Long.parseLong(contentLength);
                        ThrowUtil.throwIf(size > 2 * ONE_M, ErrorEnum.UPLOAD_FILE_OVERSIZE, "文件大小超过2MB");
                    } catch (Exception e) {
                        throw new BusinessException(ErrorEnum.PARAM_CHECK_MISTAKE, "文件大小格式错误");
                    }
                }
            }
        } catch (Exception e) {
            log.error("url图片上传验证非法:{}", e.getMessage());
            throw new BusinessException(ErrorEnum.PARAM_CHECK_MISTAKE,"url图片上传验证非法");
        } finally {
            if (response != null) {
                response.close();
            }
        }

    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String pictureUrl = (String) inputSource;
        return FileUtil.mainName(pictureUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception{
        String pictureUrl = (String) inputSource;
        //处理转义字符
        int questionMarkIndex = pictureUrl.indexOf("?");
        if (questionMarkIndex > -1) {
            pictureUrl = pictureUrl.substring(0, questionMarkIndex);
        }
        HttpUtil.downloadFile(pictureUrl,file);
    }
}
